// pages/student/course-detail/course-detail.js
import { courses, difficultyMap } from '../../../utils/mockData.js'

Page({
  data: {
    course: null,
    isEnrolled: false,
    showFullDesc: false,
    currentTab: 0,
    tabs: ['课程介绍', '课程目录', '学员评价'],
    expandedChapters: [],
    showRatingModal: false,
    userRating: 5,
    userReview: ''
  },
  onLoad(options) {
    const id = parseInt(options.id)
    const course = courses.find(c => c.id === id)
    if (course) {
      // 计算总课时和总时长
      let totalLessons = 0
      let totalDuration = 0
      if (course.chapters) {
        course.chapters.forEach(chapter => {
          if (chapter.lessons) {
            totalLessons += chapter.lessons.length
            chapter.lessons.forEach(lesson => {
              if (lesson.video_duration) {
                totalDuration += lesson.video_duration
              }
            })
          }
        })
      }
      
      // 计算总小时数（保留1位小数）
      const totalHours = totalDuration > 0 ? (totalDuration / 3600).toFixed(1) : '0.0'
      
      this.setData({ 
        course: {
          ...course,
          totalLessons,
          totalDuration,
          totalHours,
          difficultyText: difficultyMap[course.difficulty_level] || '未知'
        }
      })
    }
  },
  switchTab(e) {
    const index = e.currentTarget.dataset.index
    this.setData({ currentTab: index })
  },
  toggleChapter(e) {
    const chapterId = e.currentTarget.dataset.id
    const { expandedChapters } = this.data
    const index = expandedChapters.indexOf(chapterId)
    
    if (index > -1) {
      expandedChapters.splice(index, 1)
    } else {
      expandedChapters.push(chapterId)
    }
    
    this.setData({ expandedChapters: [...expandedChapters] })
  },
  playLesson(e) {
    const { lessonId, isFree } = e.currentTarget.dataset
    
    if (!isFree && !this.data.isEnrolled) {
      wx.showToast({
        title: '请先报名课程',
        icon: 'none'
      })
      return
    }
    
    wx.navigateTo({
      url: `/pages/student/replay/replay?courseId=${this.data.course.id}&lessonId=${lessonId}`
    })
  },
  enrollCourse() {
    wx.showModal({
      title: '确认报名',
      content: `确定要报名《${this.data.course.title}》吗？`,
      confirmText: '确认支付',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '支付中...' })
          setTimeout(() => {
            wx.hideLoading()
            this.setData({ isEnrolled: true })
            wx.showToast({
              title: '报名成功',
              icon: 'success'
            })
          }, 1500)
        }
      }
    })
  },
  joinLiveRoom() {
    if (!this.data.isEnrolled) {
      wx.showToast({
        title: '请先报名课程',
        icon: 'none'
      })
      return
    }
    wx.navigateTo({
      url: `/pages/student/live-room/live-room?courseId=${this.data.course.id}`
    })
  },
  startLearning() {
    // 开始学习,进入视频播放页面
    if (!this.data.isEnrolled) {
      wx.showToast({
        title: '请先报名课程',
        icon: 'none'
      })
      return
    }
    
    // 跳转到视频播放页面,播放第一个课时或上次学习的课时
    wx.navigateTo({
      url: `/pages/student/replay/replay?courseId=${this.data.course.id}`
    })
  },
  toggleDescription() {
    this.setData({
      showFullDesc: !this.data.showFullDesc
    })
  },
  showRating() {
    if (!this.data.isEnrolled) {
      wx.showToast({
        title: '报名后才能评价',
        icon: 'none'
      })
      return
    }
    this.setData({ showRatingModal: true })
  },
  hideRating() {
    this.setData({ showRatingModal: false })
  },
  selectRating(e) {
    const rating = e.currentTarget.dataset.rating
    this.setData({ userRating: rating })
  },
  handleReviewInput(e) {
    this.setData({ userReview: e.detail.value })
  },
  submitRating() {
    const { userRating, userReview } = this.data
    
    if (!userReview.trim()) {
      wx.showToast({
        title: '请输入评价内容',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({ title: '提交中...' })
    setTimeout(() => {
      wx.hideLoading()
      this.setData({ 
        showRatingModal: false,
        userRating: 5,
        userReview: ''
      })
      wx.showToast({
        title: '评价成功',
        icon: 'success'
      })
    }, 1000)
  },
  formatDuration(seconds) {
    const minutes = Math.floor(seconds / 60)
    if (minutes < 60) {
      return `${minutes}分钟`
    }
    const hours = Math.floor(minutes / 60)
    const mins = minutes % 60
    return `${hours}小时${mins}分钟`
  }
})
